<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ForgotForm
 *
 * @author dung3625@gmail.com
 * @date 01/03/2014
 */
class ForgotForm extends CFormModel
{
    
    public $email;
    public $username;
    public $password;
    private $_identity;
    
    public function rules()
	{
		return array(
			// email are required
			array('email', 'required'),
			// email needs to be authenticated
			array('email', 'authenticate'),                                    
		);
	}
        public function attributeLabels()
	{	
	}
        public function authenticate($attribute,$params)
	{
		if(!$this->hasErrors())
		{
			$this->_identity=new EmailIdentity($this->email);
			if(!$this->_identity->authenticate())
				$this->addError('email','Incorrect email.');
		}
	}
        public function forgot() {
            if($this->_identity===null)
	{
	$this->_identity=new EmailIdentity($this->email);
	$this->_identity->authenticate();
	}
            if($this->_identity->errorCode===NULL)
	{
                //connect database lay username va password
                     try{
                        $connection=Yii::app()->db;   // assuming you have configured a "db" connection
                        $query="SELECT os_users.username,os_users.password, os_users.name FROM os_users  WHERE os_users.email='{$this->email}' limit 1 ";
                        $command=$connection->createCommand($query);
                        $dataReader=$command->query();
                        $rows_user = array();
                        while(($row=$dataReader->read())!==false) {
                            $rows_user[]=$row;
                        }      
                        $this->username = $rows_user[0]['username'];
                        $this->password = $rows_user[0]['password'];
                       
                        //send email
                        //date 12/03/2014
                        $message = new YiiMailMessage;
                        $message->setBody("Gửi: {$rows_user[0]['name']}<br>Account: {$this->username}<br>Password: {$this->password}", 'text/html');
                        $message->subject = 'Forgot password';
                        $message->addTo($this->email);
                        $message->setFrom(array(Yii::app()->params['adminEmail'] => 'Admin Order System'));    //Yii::app()->params['adminEmail'];
                        Yii::app()->mail->send($message);       
                     return true;
                    }catch(Exception $e){}
	}
            else
	return false;
        }
    
}

?>
